<?php

/* name: 注册用户信息管理 
 * author: wangbin
 *  time:2015年6月16日 
 */
//访问权限标识
define(C("ACCESSACTION"), true);
import('jinghuan.Hxapi');

class ActivemanageAction extends CommonAction {

    function _initialize() {
        $this->auth_allow_function[] = 'set_sort';
        $this->auth_allow_function[] = 'do_set_sort';
        $this->auth_allow_function[] = 'do_add_image';
        $this->auth_allow_function[] = 'do_add_image_';
        $this->auth_allow_function[] = 'details';
        $this->auth_allow_function[] = 'upload';
        $this->auth_allow_function[] = 'do_upload';
        $this->auth_allow_function[] = 'save_image';
        $this->auth_allow_function[] = 'add_group';
        $this->do_edit = $this->do_add = array(
            'sponsor' => array(
                array('name' => Validate::REQUIRED, 'value' => true),
            ),
            'title' => array(
                array('name' => Validate::REQUIRED, 'value' => true),
            ),
            'money' => array(
                array('name' => Validate::REQUIRED, 'value' => true),
            ),
            'number' => array(
                array('name' => Validate::REQUIRED, 'value' => true),
            ),
            'address' => array(
                array('name' => Validate::REQUIRED, 'value' => true),
            ),
            'active_status' => array(
                array('name' => Validate::REQUIRED, 'value' => true),
            )
        );
        $this->do_set_sort = array(
            'sort' => array(
                array('name' => Validate::REQUIRED, 'value' => true),
                array('name' => Validate::DIGITS, 'value' => true),
            )
        );
        $this->do_send_message = array(
            'content' => array(
                array('name' => Validate::REQUIRED, 'value' => true)
            ),
        );
        parent::_initialize();
    }

    function index() {
        if ($this->isAjax()) {
            $this->active_type = D(TABLE_SOURCE_BASIC_FIELD)->field("concat(group_id,id) as id,name")->where("group_id=1007")->select();
            $this->active_status = $s = D(TABLE_SOURCE_BASIC_FIELD)->field("concat(group_id,id) as id, name")->where(array("group_id" => 1009))->select();
            $this->callback($this->fetch());
        }
    }

    function datatable() {
        if ($this->isAjax()) {
            $post = post_datatable();
            foreach ($post['sql_where'] as $f => $v) {
                if (!empty($v)) {
                    if ($f === 'active_type_id') {
                        $post["sql_where"][$f] = array('EQ', $v);
                    } else {
                        $post["sql_where"][$f] = array('exp', "like '%" . $v . "%'");
                    }
                }
            }
            $post["sql_where"]['status'] = 1;
            $voList = V("Activemanage")
                    ->where($post["sql_where"])
                    ->order($post["sql_order"])
                    ->limit($post["sql_limit"])
                    ->select();
            //      $this->func("$.Log", print_r(D()->getLastSql(), TRUE));
            $count = V("Activemanage")
                    ->where($post["sql_where"])
                    ->order($post["sql_order"])
                    ->select();
            foreach ($voList as $k => $v) {
                if ($v['img']) {
                    $voList[$k]["tipimage"] = C('ACTIVE_IMAGE_PATH') . $v['img'];
                    $voList[$k]["img"] = '<img data-path="' . C('ACTIVE_IMAGE_PATH') . $v['img'] . '" src="' . $voList[$k]["tipimage"] . '" style="height:50px;width:50px">';
                }
                if ($v['image']) {
                    $voList[$k]["tipimage2"] = C('ACTIVE_IMAGE_PATH') . $v['image'];
                    $voList[$k]["image"] = '<img data-path="' . $voList[$k]["tipimage2"] . '" src="' . $voList[$k]["tipimage2"] . '" style="height:50px;width:50px">';
                }
            }

            $this->callback(datatable($voList, $post["sEcho"], count($count)));
        }
    }

    function get_image() {
        if ($this->isAjax()) {
            $this->path = $this->_q('path');

            $this->callback($this->fetch());
        }
    }

    function edit() {
        if ($this->isAjax()) {
            $this->id = $id = $this->_q("id");
            //      $this->func("$.Log",  print_r($id,TRUE));
            $this->active_type = D(TABLE_SOURCE_BASIC_FIELD)->field("concat(group_id,id) as id, name")->where(array("group_id" => 1007))->select();
            $this->data = D(TABLE_ACTIVE_ACTIVE_NAME)
                            ->field("id,img,active_type_id,title,content,FROM_UNIXTIME(b_time) as b_time,FROM_UNIXTIME(e_time) as e_time,user_id,time,u_time,status,active_status_id,praise,address,money,number,sponsor,groupid")
                            ->where(array("id" => $id))->find();
            $this->active_status = $s = D(TABLE_SOURCE_BASIC_FIELD)->field("concat(group_id,id) as id, name")->where(array("group_id" => 1009))->select();
            $this->callback($this->fetch());
        }
    }

    function do_edit() {
        if ($this->isAjax()) {
            $data = $this->_q();
            $this->func("$.Log", print_r($data, TRUE));
            //环信编辑群
            $hx = new Hxapi();
            $data_['group_id'] = $data['groupid'];
            $data_['groupname'] = $data['title'];
            $data_['descscription'] = '';
            if ($data["number"] < 1980) {
                $num = $data["number"] + 20;
            } else {
                $num = 2000;
            }
            $data_['maxusers'] = $num;
            $res = $hx->update_chatgroups($data_);
//            if ($res === 0) {
//                $res_ = 0;
//            } else {
            $xdata = D(TABLE_ACTIVE_ACTIVE_NAME)
                    ->where(array("id" => $data["id"]))
                    ->save(array(
                "active_type_id" => $data["active_type_id"],
                "title" => $data["title"],
                "b_time" => strtotime($data["b_time"]),
                "e_time" => strtotime($data["e_time"]),
                "active_status_id" => $data["active_status_id"],
                "content" => str_replace(C('HOST'), '', $data["content"]),
                "u_time" => time(),
                "praise" => $data["praise"],
                "address" => $data["address"],
                "number" => $data["number"],
                "money" => $data["money"],
                "user_id" => $_SESSION["USER_AUTH_KEY"],
                "sponsor" => $data["sponsor"]
            ));

            if ($xdata === false) {
                $res_ = 0;
            } else {
                $res_ = 1;
            }
//            }
            if ($res_ === 1) {
                $this->edit_success();
                $this->callback();
            } else {
                $this->edit_error();
            }
        }
    }

    function add() {
        if ($this->isAjax()) {
            $this->time = date("Y-m-d H:i:s", time());
            $this->active_type = D(TABLE_SOURCE_BASIC_FIELD)->field("concat(group_id,id) as id, name")->where(array("group_id" => 1007))->select();
            $this->active_status = $s = D(TABLE_SOURCE_BASIC_FIELD)->field("concat(group_id,id) as id, name")->where(array("group_id" => 1009))->select();
            $this->callback($this->fetch());
        }
    }

    function do_add() {
        if ($this->isAjax()) {
            $data = $this->_q();
            $this->func("$.Log", print_r($data, TRUE));
            //环信创建群
            $hx = new Hxapi();
            $data_['groupname'] = $data['title'];
            $data_['descscription'] = '';
            if ($data["number"] < 1980) {
                $num = $data["number"] + 20;
            } else {
                $num = 2000;
            }
            $data_['maxusers'] = $num;
            $data_['owner'] = '10000';
            $res = $hx->add_chatgroups($data_);

//            if (empty($res['groupid'])) {
//                $res_ = 0;
//            } else {
            $xdata = D(TABLE_ACTIVE_ACTIVE_NAME)->add(array(
                "active_type_id" => $data["active_type_id"],
                "title" => $data["title"],
                "content" => $data["content"],
                "b_time" => strtotime($data["b_time"]),
                "e_time" => strtotime($data["e_time"]),
                "time" => time(),
                "praise" => $data["praise"],
                "address" => $data["address"],
                "number" => $data["number"],
                "money" => $data["money"],
                "user_id" => $_SESSION["USER_AUTH_KEY"],
                "active_status_id" => $data["active_status_id"],
                "sponsor" => $data["sponsor"],
                "groupid" => $res["groupid"]
            ));
            if ($xdata === false) {
                $res_ = 0;
                $data1_['group_id'] = $res["groupid"];
                $hx->delete_chatgroups($data1_);
            } else {
                $res_ = 1;
            }
//            }

            if ($res_ === 1) {
                $this->add_success();
                $this->callback();
            } else {
                $this->add_error();
            }
        }
    }

    function do_delete() {
        if ($this->isAjax()) {
            $data = $this->_q();
            $xdata = D(TABLE_ACTIVE_ACTIVE_NAME)
                    ->where(array("id" => $data["id"]))
                    ->save(array(
                "status" => 0,
                "active_status_id" => 0
            ));
            if ($xdata === false) {
                $this->del_error();
            } else {
                $this->del_success();
                $this->callback();
            }
        }
    }

    function do_add_image() {
        if (isAjax()) {
            $data["id"] = $this->_q("id");
            $data["img"] = $this->_q("image");
            $d = D(TABLE_ACTIVE_ACTIVE_NAME)->save($data);
            if ($d === false) {
                $this->add_error();
            } else {
                $this->add_success();
                $this->callback();
            }
        }
    }
    
    function do_add_image_() {
        if (isAjax()) {
            $data["id"] = $this->_q("id");
            $data["image"] = $this->_q("image");
            $d = D(TABLE_ACTIVE_ACTIVE_NAME)->save($data);
            if ($d === false) {
                $this->add_error();
            } else {
                $this->add_success();
                $this->callback();
            }
        }
    }

    /**
     * 文章详情
     */
    function details() {
        if ($this->isAjax()) {
            $this->data = D(TABLE_ACTIVE_ACTIVE_NAME)->where(array('id' => $this->_q('id'), 'status' => 1))->field('content')->find();
            $this->callback($this->fetch());
        }
    }

//    function set_top() {
//        $data = $this->_q();
//        D(TABLE_ACTIVE_ACTIVE_NAME)->where(array('id' => $data['id']))->save(array('sort' => time()));
//        $this->callback(true);
//    }

    function set_sort() {
        if ($this->isAjax()) {
            $this->id = $id = $this->_q("id");
            $this->data = D(TABLE_ACTIVE_ACTIVE_NAME)
                            ->field("id,title,sponsor,sort")
                            ->where(array("id" => $id))->find();
            $this->callback($this->fetch());
        }
    }

    function do_set_sort() {
        if ($this->isAjax()) {
            $data = $this->_q();
            D(TABLE_ACTIVE_ACTIVE_NAME)->where(array('id' => $data['id']))->save(array('sort' => $data['sort']));
            $this->callback(true);
        }
    }

    function send_message() {
        if ($this->isAjax()) {
            $id = $this->_q("id");
            $this->groupid = D(TABLE_ACTIVE_ACTIVE_NAME)->where(array('id' => $id))->getField('groupid');
            $this->callback($this->fetch());
        }
    }

    function do_send_message() {
        if ($this->isAjax()) {
            $post = $this->_q();
            if (!empty($post['content'])) {
                $hx = new Hxapi();
                $data['target_type'] = 'chatgroups';
                $data['target'][] = $post['groupid'];
                $data['msg']['type'] = 'txt';
                $data['msg']['msg'] = $post['content'];
                $data['from'] = '10000';
                $data['ext']['imageAttribute'] = C('HOST') . "/logo.png";
                $data['ext']['nickAttribute'] = '50+团队';
                $data['ext']['msgtype'] = '0';
                $res = $hx->sendmessage($data);
                if ($res[$post['groupid']]) {
                    $this->success('发送成功');
                    $this->callback();
                } else {
                    $this->error('发送失败');
                }
            } else {
                $this->error('内容不能为空');
            }
        }
    }

    function upload() {
        if ($this->isAjax()) {
            $this->id = $id = $this->_q('id');
            $image = D(TABLE_ACTIVE_ACTIVE_NAME)->where(array('id' => $id))->getField('image');
            $image = $image ? C('HOST') . C('ACTIVE_IMAGE_PATH') . $image : C('HOST') . '/images/none_img.jpg';
            $this->assign('image', $image);
            $this->callback($this->fetch(), $id);
        }
    }

    function do_upload() {
        $id = $this->_q('id');
        $path = clean_path(APP_PATH . C('ACTIVE_IMAGE_PATH'));
        createdir($path);

        //上传的路径设置
        if (!empty($_FILES ['Filedata'] ['name'])) {
            $tmp_file = $_FILES ['Filedata'] ['tmp_name'];
            $file_types = explode(".", $_FILES ['Filedata'] ['name']);
            $file_type = $file_types [count($file_types) - 1];
            //判别是不是.xls文件，判别是不是excel文件
            // 设置上传路径
            // $savePath = APP_PATH . $UPLOAD['excel'];
            $savePath = $path;

            //以时间来命名上传的文件
            $str = date('Ymdhis');
            $file_name = md5($id) . ".jpg";

            //是否上传成功
            if (!copy($tmp_file, $savePath . $file_name)) {
//                $return["status"] = 0;
                $this->error('上传失败');
            } else {
//                $return["status"] = 1;
                $return["url"] = C('HOST') . C('ACTIVE_IMAGE_PATH') . $file_name . '?' . time();
                $return["name"] = $file_name;
            }
            // if ($return["status"] == 0) {
            // $return["status"] = 0;
            // $this->func("$.error", "add_error");
            // } else {
            // $return["file_url"] = $savePath . $file_name;
            // }
            echo json_encode($return);
        }
    }

    function save_image() {
        if (isAjax()) {
            $data = $this->_q();
            $d = D(TABLE_ACTIVE_ACTIVE_NAME)->save($data);
            if ($d === false) {
                $this->set_error();
            } else {
                $this->set_success();
                $this->callback();
            }
        }
    }

    function add_group() {
        if (isAjax()) {
            $id = $this->_q("id");
            $act = D(TABLE_ACTIVE_ACTIVE_NAME)->where(array('id' => $id))->field('title,number')->find();
            //环信创建群
            if (!empty($act)) {
                $hx = new Hxapi();
                $data_['groupname'] = $act['title'];
                $data_['descscription'] = '';
                if ($act["number"] < 1980) {
                    $num = $act["number"] + 20;
                } else {
                    $num = 2000;
                }
                $data_['maxusers'] = $num;
                $data_['owner'] = '10000';
                $res = $hx->add_chatgroups($data_);
                if (empty($res['groupid'])) {
                    $res_ = 0;
                } else {
                    $xdata=D(TABLE_ACTIVE_ACTIVE_NAME)->where(array('id'=>$id))->save(array('groupid'=>$res['groupid']));
                    if($xdata===false){
                        $res_ = 0;
                    }else{
                        $res_ = 1;
                    }
                }
            } else {
                $res_ = 0;
            }
            if ($res_ === 1) {
                $this->success('创建群成功');
                $this->callback();
            } else {
                $this->error('创建群失败');
            }
        }
    }

}
